<template>
  <div>
    <div class="main-container-no-bg">
      <el-row :gutter="15">
        <el-col :span="24">
          <div class="education-box">
            <div class="title">{{ resourceInfo.title }}</div>
            <el-row :gutter="30" class="desc">
              <el-col :span="8">来源：{{ resourceInfo.source }}</el-col>
              <el-col :span="10"
                >发布时间：{{ resourceInfo.releaseTime }}</el-col
              >
              <el-col :span="6">阅读量：{{ resourceInfo.readNumber }}次</el-col>
            </el-row>
            <div class="line"></div>
            <div class="video_main">
              <video-player
                v-if="resourceInfo.fileType === 1"
                class="video-player vjs-custom-skin"
                :class="{ 'my-custom-class': shouldApplyCustomClass }"
                ref="videoPlayer"
                :playsinline="true"
                :options="playerOptions"
                @timeupdate="onTimeUpdate($event)"
                @ended="onEnded"
              />
            </div>

            <div
              v-if="resourceInfo.fileType === 2"
              @click="handleDownload"
              style="cursor: pointer; color: #a52529"
            >
              点击下载资源文档
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getResourceInfo, listResourceInfo } from "@/api/business/resourceInfo";
import { addResourceProgress } from "@/api/business/resourceProgress";

export default {
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      resourceInfo: {},
      resourceInfoList: [],
      playerOptions: {
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4", // 类型
            src: this.videoSrc, // url地址
          },
        ],
        poster: "", // 封面地址
        width: document.documentElement.clientWidth,
        notSupportedMessage: "加载中......", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          currentTimeDisplay: true,
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
      },
      shouldApplyCustomClass: true, // 控制是否应用自定义类
      timer: null,
    };
  },
  created() {
    this.getInfo(this.$route.query.id);
    this.getList();
  },
  methods: {
    getInfo(id) {
      getResourceInfo(id).then((response) => {
        this.resourceInfo = response.data;
        if (this.resourceInfo.attachment.indexOf("/profile") > -1) {
          this.playerOptions.sources[0].src =
            this.baseURL + this.resourceInfo.attachment;
        } else {
          this.playerOptions.sources[0].src = this.resourceInfo.attachment;
        }
        if (this.resourceInfo.progress >= 100) {
          this.shouldApplyCustomClass = false;
        }
      });
    },
    getList() {
      let queryParams = {
        pageNum: 1,
        pageSize: 10,
        isShow: 1,
      };
      listResourceInfo(queryParams).then((response) => {
        this.resourceInfoList = response.rows;
      });
    },
    handleDownload() {
      window.open(this.baseURL + this.resourceInfo.attachment);
    },
    toPage(url) {
      this.$router.push(url);
    },

    onTimeUpdate(player) {
      if (this.timer) {
        return;
      }
      this.timer = true;
      setTimeout(() => {
        this.timer = false;
        let progress = Math.min(
          ((player.currentTime() / player.duration()) * 100).toFixed(2),
          100
        );
        this.updateProgress(progress);
      }, 2000);
    },
    onEnded() {
      this.updateProgress(100);
    },
    updateProgress(progress) {
      // 封装 addResourceProgress 调用
      addResourceProgress({
        resourceId: this.resourceInfo.id,
        progress: progress,
      })
        .then(() => {
          // console.log('Resource progress updated.');
          if (progress >= 100) {
            this.shouldApplyCustomClass = false; // 确保在这里也设置
          }
        })
        .catch((error) => {
          console.error("Failed to update resource progress:", error);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.main-container-no-bg {
  padding: 0 100px 30px 100px;
  box-sizing: border-box;
}

.education-box {
  padding: 50px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 5px 5px 10px 0 rgba(157, 156, 156, 0.1);

  .title {
    text-align: center;
    font-size: 26px;
    font-weight: bolder;
    margin-top: 30px;
    margin-bottom: 30px;
  }

  .desc {
    text-align: center;
    color: rgba(121, 121, 121, 1);
    margin-bottom: 30px;
  }

  .line {
    border-bottom: 2px dashed rgba(121, 121, 121, 1);
    margin-bottom: 30px;
  }

  .content {
    line-height: 35px;
    text-indent: 2em;
    min-height: 500px;
    font-family: "Microsoft YaHei";
    white-space: pre-line;
  }
}

.my-custom-class ::v-deep .vjs-progress-control {
  pointer-events: none !important;
}
::v-deep .video-js .vjs-play-progress:before {
  line-height: normal;
}
</style>
